#!/bin/bash

URL="$1"
if [ -z "$URL" ]; then
    echo "未传入URL"
    exit 1
fi

# 获取下载文件夹路径
if [ -f "$HOME/.config/user-dirs.dirs" ]; then
    source "$HOME/.config/user-dirs.dirs"
    TEMP_DIR=$(eval echo "$XDG_DOWNLOAD_DIR")
else
    TEMP_DIR="$HOME/Downloads"
fi

# 确保下载文件夹存在
mkdir -p "$TEMP_DIR"

# 进入下载目录
cd "$TEMP_DIR" || {
    echo "无法进入下载目录: $TEMP_DIR"
    exit 1
}

# 下载文件
if ! wget -q --show-progress --content-disposition "$URL"; then
    echo "下载失败！请检查URL是否有效"
    exit 1
fi

FILENAME=$(ls -t | head -n 1)

# 安装逻辑
if [[ "$FILENAME" == *.deb ]]; then
    if ! apt install -y "./$FILENAME"; then
        echo "DEB包安装失败"
        exit 1
    fi
elif [[ "$FILENAME" == *.rpm ]]; then
    if ! dnf install -y "./$FILENAME"; then
        echo "RPM包安装失败"
        exit 1
    fi
else
    echo "不支持的文件类型！仅支持.deb和.rpm"
    exit 1
fi

echo "安装完成"